define(['./config', 'underscore', 'backbone'], function(config, _, Backbone) {
  var app;

  function ApiManager(_app) {
    app = _app;
    // this.loadWeiboApi();
  }

  _.extend(ApiManager.prototype, Backbone.Events);

  Backbone.sync = function(method, model, options) {
    options || (options = {});
    switch (method) {
      case 'create':
        WeiboRequest('post', model.url, _.clone(model.attributes), options);
        break;
      case 'update': 
        WeiboRequest('post', model.url, _.clone(model.attributes), options);
        break;
      case 'delete':
        WeiboRequest('post', '/statuses/destroy.json', {id:model.attributes.id}, options);
        break;
      case 'read':
        WeiboRequest('get', model.url, options.data, options);
        break;
    }
  }

  function WeiboRequest(method, url, data, options) {
    WB2.anyWhere(function(W) {
      //数据交互
      W.parseCMD(url, function(oResult, bStatus) {
        if (bStatus) {
          //这里的options.success已经不我在外面写的了，而是经过封装的
          //这里调用了，需要在外面先取到model，再用model.get('key')取值
          //options.error还不知道怎么取
          if (oResult.error_code)
            options.success(oResult, true);
          else
            options.success(oResult.statuses || oResult.comments || oResult, true);
        } else {
          if (options.error) options.error(oResult);
        }
      }, data, {
        method: method,
        cache_time: 30
      });
    });
  }

  ApiManager.prototype.init = function() {
    this.checkAuth();
  }

  ApiManager.prototype.checkAuth = function() {
    var status = WB2.checkLogin();
    if (status) {
      app.views.auth.$el.hide();
      $('#signed-in-container').show();
      this.trigger('ready');
    } else {
      app.views.auth.$el.show();
      $('#signed-in-container').hide();
    }
  }

  ApiManager.prototype.auth = function() {
    WB2.login(this.checkAuth);
  }

  ApiManager.prototype.loadWeiboApi = function() {
    if (typeof WB2 != 'undefined') {
      return this.init();
    }

    var self = this;

    require([
      'http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=' + config.appKey + '&debug=true'
    ], function() {
      function checkWeiboApi() {
        if (WB2 && WB2.login) {
          self.init();
        } else {
          setTimeout(checkWeiboApi, 100);
        }
      }

      checkWeiboApi();
    })
  }

  return ApiManager;
})
